package com.homestay.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*", dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD})
public class LoginFilter implements Filter {

    // 不需要登录验证的路径（白名单）
    private static final String[] WHITE_LIST = {
            "/login.jsp",
            "/admins",
            "/views/register.jsp",
            "/CodeServlet.do",
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取请求的URI
        String uri = req.getRequestURI();

        // 检查是否在白名单中
        if (isInWhiteList(uri)) {
            // 白名单中的路径，直接放行
            chain.doFilter(request, response);
            return;
        }

        // 不在白名单中，检查用户是否已登录
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        // System.out.println("username:"+username);
        if (username == null) {
            // 未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }

        // 已登录，继续执行
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁操作
    }

    /**
     * 检查URI是否在白名单中
     * @param uri 请求的URI
     * @return 是否在白名单中
     */
    private boolean isInWhiteList(String uri) {
        for (String whitePath : WHITE_LIST) {
            if (uri.contains(whitePath)) {
                return true;
            }
        }
        return false;
    }
}
